import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:isolate_manager/isolate_manager.dart';
import 'package:pitchertools/dao/data_manager.dart';
import 'package:pitchertools/http/api.dart';

import '../../http/dio_http.dart';
import '../../models/fans_query_bean.dart';
import 'index.dart';

@isolateManagerWorker
getFansData(int index, String url, Map<String, String> params) {
  final controller = Get.find<QueryFansController>();
  List<FansQueryBean> fansQueryBeanList =
      controller.state.fansQueryBeanListRx ?? [];
  DioHttp.cget(url, queryParameters: params).then((rp) {
    if (rp == null || rp['list'] == null) {
      // completedNum++;

      // if (completedNum >= fansQueryBeanList.length) {
      //   SmartDialog.dismiss();
      // }
      return;
    }

    List apiMsgs = rp['list']['rows'];
    if (apiMsgs.isEmpty) {
      // completedNum++;
      // if (completedNum >= fansQueryBeanList.length) {
      //   SmartDialog.dismiss();
      // }
      return;
    }
    var apiMsg = apiMsgs[0];

    print(apiMsg);
    fansQueryBeanList[index].csName = apiMsg['csName'];
    fansQueryBeanList[index].addFansNow = apiMsg['addCountNow'];
    fansQueryBeanList[index].repeatFansNow = apiMsg['repCountNow'];
    fansQueryBeanList[index] = fansQueryBeanList[index];
    // completedNum++;
    // if (completedNum >= fansQueryBeanList.length) {
    //   SmartDialog.dismiss();
    // }
  });
}

class QueryFansController extends GetxController {
  QueryFansController();

  final state = QueryFansState();

  final SmartDialogController smartDialogController = SmartDialogController();

  getLoginImgByteData() async {
    SmartDialog.showLoading(clickMaskDismiss: true);
    var rp = await DioHttp.cget(Api.DAMAI_LOGIN_CAPTCHA_IMAGE);

    print(rp);
    state.imgByteData = rp["img"];
    state.loginUUID = rp["uuid"];
    SmartDialog.dismiss();
  }

  /// 刷新粉丝数据
  refreshFansData() {
    List<FansQueryBean> fansQueryBeanList = state.fansQueryBeanListRx ?? [];
    FansQueryBean item;
    if (fansQueryBeanList.isNotEmpty) {
      SmartDialog.showLoading(
          clickMaskDismiss: true, controller: smartDialogController);
    }

    int completedNum = 0;

    // final isolateShared = IsolateManager.createShared(
    //     concurrent: 4,
    //     useWorker: true,
    //     workerMappings: {
    //       getFansData: 'getFansData',
    //     });

    for (var i = 0; i < fansQueryBeanList.length; i++) {
      item = fansQueryBeanList[i];
      if (item.queryApiType == FansQueryApiType.HaiWang) {
      } else if (item.queryApiType == FansQueryApiType.DaMai) {
        String url = item.queryApiUrl + item.csNumber;
        var queryParameters = {
          "params[beginTime]": item.startDate,
          "params[endTime]": item.endDate,
        };

        //发起请求
        DioHttp.cget(url, queryParameters: queryParameters).then((rp) {
          if (rp == null || rp['list'] == null) {
            completedNum++;

            if (completedNum >= fansQueryBeanList.length) {
              SmartDialog.dismiss();
            }
            return;
          }

          List apiMsgs = rp['list']['rows'];
          if (apiMsgs.isEmpty) {
            completedNum++;
            if (completedNum >= fansQueryBeanList.length) {
              SmartDialog.dismiss();
            }
            return;
          }
          var apiMsg = apiMsgs[0];

          print(apiMsg);
          fansQueryBeanList[i].csName = apiMsg['csName'];
          fansQueryBeanList[i].addFansNow = apiMsg['addCountNow'];
          fansQueryBeanList[i].repeatFansNow = apiMsg['repCountNow'];
          fansQueryBeanList[i] = fansQueryBeanList[i];
          completedNum++;
          if (completedNum >= fansQueryBeanList.length) {
            SmartDialog.dismiss();
          }
        });
      }
    }
  }

  /// 从服务器上获取粉丝查询api列表
  Future<List<dynamic>> getFansQueryApiMsgs() async {
    var rp = await DioHttp.cget(
      Api.QUERY_FANS_API_JSON,
    );
    // print(rp);
    if (rp == null || rp['version'] == null) {
      return [];
    }
    return rp['fansQueryApiMsgs'];
  }

  /// 从服务器上获取账号列表
  Future<List<dynamic>> getAccountMsgs() async {
    var rp = await DioHttp.cget(
      Api.ACCOUNTS_API_JSON,
    );
    // print(rp);
    if (rp == null || rp['version'] == null) {
      return [];
    }
    return rp['accounts'];
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  Future<void> onInit() async {
    super.onInit();
    //获取本地存储的数据
    List<String> fansQueryBeanList = DataManager.getFansQueryBeanList();

    state.fansQueryBeanList =
        fansQueryBeanList.map((e) => FansQueryBean.fromJsonString(e)).toList();
    // 获取粉丝查询api列表
    state.fansQueryApiMsgs = await getFansQueryApiMsgs();
    // 获取账号列表
    state.accountMsgs = await getAccountMsgs();
    // 刷新粉丝数据
    refreshFansData();

    //获取Authorization并设置
    String authorization = DataManager.getAuthorization();
    if (authorization.isNotEmpty) {
      DioHttp.setDefaultHeader("Authorization", authorization);
    }
  }

  /// 保存Authorization
  /// @param authorization
  saveAuthorization(String authorization) {
    // 持久化
    DataManager.saveAuthorization(authorization);
    // 设置header
    DioHttp.setDefaultHeader("Authorization", authorization);
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    //持久化页面数据
    List<FansQueryBean> fansQueryBeanList = state.fansQueryBeanListRx.value;
    List<String> fansQueryBeanStrList =
        fansQueryBeanList.map((e) => e.toJsonString()).toList();
    DataManager.setFansQueryBeanList(fansQueryBeanStrList);
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
